﻿@{
    ViewData["Title"] = "Home Page";
}

<div class="row">
    <div class="col-sm-6 col-md-4 col-lg-3">
        <div class="form-group">
            <label for="appId" class="control-label">AppId</label>
            <input type="text" class="form-control" id="appId" placeholder="请输入AppId" value="wx52d8883b88a4f717" />
        </div>
    </div>
    <div class="col-sm-6 col-md-4 col-lg-3">
        <div class="form-group">
            <label for="secret" class="control-label">Secret</label>
            <input type="text" class="form-control" id="secret" placeholder="请输入Secret" value="9fd91a73c284597f94b842b9f7ab8f26" />
        </div>
    </div>
</div>

<div class="row">
    <div class="col-sm-12 col-md-12 col-lg-12">
        <div class="form-group">
            <label for="resultMenu" class="control-label">自定义菜单：</label>
            <textarea class="form-control" rows="5" id="resultMenu" name="text"></textarea>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-sm-6 col-md-4 col-lg-3">
        <div class="form-group">
            <input type="button" class="btn btn-dark" id="btnGetMenus" value="获取菜单" />
        </div>
    </div>
    <div class="col-sm-6 col-md-4 col-lg-3">
        <div class="form-group">
            <input type="button" class="btn btn-dark" id="btnCreateMenus" value="创建菜单" />
        </div>
    </div>
    <div class="col-sm-6 col-md-4 col-lg-3">
        <div class="form-group">
            <input type="button" class="btn btn-dark" id="btnDeleteMenus" value="删除菜单" />
        </div>
    </div>
    <div class="col-sm-6 col-md-4 col-lg-3">
        <div class="form-group">
            <input type="button" class="btn btn-dark" id="btnGetApiDomainIp" value="获取微信API接口IP地址" />
        </div>
    </div>
    <div class="col-sm-6 col-md-4 col-lg-3">
        <div class="form-group">
            <input type="button" class="btn btn-dark" id="btnGetCallBackIp" value="获取微信callback IP地址" />
        </div>
    </div>
    <div class="col-sm-6 col-md-4 col-lg-3">
        <div class="form-group">
            <input type="button" class="btn btn-dark" id="btnCallBackCheck" value="网络检测" />
        </div>
    </div>
</div>

<div class="row">
    <div class="col-sm-12 col-md-12 col-lg-12">
        <div class="form-group">
            <label for="resultText" class="control-label">返回结果：</label>
            <textarea class="form-control" rows="5" id="resultText" name="text" readonly="readonly"></textarea>
        </div>
    </div>
</div>

@section Scripts {
    <script type="text/javascript">
        $(document).ready(function(){
            $("#btnGetMenus").click(function(){
                GetMenus();
            });
            $("#btnCreateMenus").click(function(){
                CreateMenus();
            });
            $("#btnDeleteMenus").click(function(){
                DeleteMenus();
            });
            $("#btnGetApiDomainIp").click(function(){
                GetApiDomainIp();
            });
            $("#btnGetCallBackIp").click(function(){
                GetCallBackIp();
            });
            $("#btnCallBackCheck").click(function(){
                CallBackCheck();
            });
        });

        async function GetApiDomainIp()
        {
            var appId = $("#appId").val();
            var secret = $("#secret").val();

            var result = await fetchWithToken('/MP/Common/GetApiDomainIp?appid='+appId+'&secret='+secret);
            console.log(result);
            if(result.Success)
            {
                var data = result.ResData;
                console.log(data);
                const prettyJsonString = JSON.stringify(data, null, 2); // 第二个参数是replacer，第三个参数是空格数，用于缩进
                console.log(prettyJsonString);
                $("#resultText").val(prettyJsonString);
            }
        }

        async function GetCallBackIp()
        {
            var appId = $("#appId").val();
            var secret = $("#secret").val();

            var result = await fetchWithToken('/MP/Common/GetCallBackIp?appid='+appId+'&secret='+secret);
            console.log(result);
            if(result.Success)
            {
                var data = result.ResData;
                console.log(data);
                const prettyJsonString = JSON.stringify(data, null, 2); // 第二个参数是replacer，第三个参数是空格数，用于缩进
                $("#resultText").val(prettyJsonString);
            }
        }

        async function CallBackCheck()
        {
            var appId = $("#appId").val();
            var secret = $("#secret").val();

            var result = await fetchWithToken('/MP/Common/CallBackCheck?appid='+appId+'&secret='+secret);
            console.log(result);
            if(result.Success)
            {
                var data = result.ResData;
                console.log(data);
                const prettyJsonString = JSON.stringify(data, null, 2); // 第二个参数是replacer，第三个参数是空格数，用于缩进
                $("#resultText").val(prettyJsonString);
            }
        }

        async function GetMenus()
        {
            var appId = $("#appId").val();
            var secret = $("#secret").val();

            var result = await fetchWithToken('/MP/Menu/GetMenus?appid='+appId+'&secret='+secret);
            console.log(result);
            if(result.Success)
            {
                var data = result.ResData;
                console.log(data);
                var menus = data.selfmenu_info;
                console.log(menus);
                //console.log(menus[0].sub_button);
                //console.log(menus[0].sub_button[0].key);
                const prettyJsonString = JSON.stringify(menus, null, 2); // 第二个参数是replacer，第三个参数是空格数，用于缩进
                $("#resultMenu").val(prettyJsonString);
            }
            else
            {
                console.log("错误码："+result.ErrCode+"；错误信息："+result.ErrMsg);
            }
        }

        async function CreateMenus()
        {
            var appId = $("#appId").val();
            var secret = $("#secret").val();
            var menus = $("#resultMenu").val();
            console.log(menus);
            var result = await fetchWithToken('/MP/Menu/CreateMenus', 'POST', { appid: appId, secret:secret, menus:menus });
            console.log(result);
            if(result.Success)
            {
                var data = result.ResData;
                console.log(data);
                const prettyJsonString = JSON.stringify(data, null, 2); // 第二个参数是replacer，第三个参数是空格数，用于缩进
                $("#resultText").val(prettyJsonString);
            }
            else
            {
                console.log("错误码："+result.ErrCode+"；错误信息："+result.ErrMsg);
            }
        }

        async function DeleteMenus()
        {
            var appId = $("#appId").val();
            var secret = $("#secret").val();
            var result = fetchWithToken('/MP/Menu/DeleteMenu?appid='+appId+'&secret='+secret);
            console.log(result);
            if(result.Success)
            {
                var data = JSON.parse(result.ResData);
                console.log(data);
                $("#resultText").val("");
            }
            else
            {
                console.log("错误码："+result.ErrCode+"；错误信息："+result.ErrMsg);
            }
        }

        function formatDate(date) {
            const year = date.getFullYear();
            const month = date.getMonth() + 1; // 注意：getMonth()方法返回的是从0开始的月份
            const day = date.getDate();
            const hours = date.getHours();
            const minutes = date.getMinutes();
            const seconds = date.getSeconds();
            const milliseconds = date.getMilliseconds();

            return `${year}-${month<10?"0":""}${month}-${day<10?"0":""}${day} ${hours<10?"0":""}${hours}:${minutes<10?"0":""}${minutes}:${seconds<10?"0":""}${seconds}.${milliseconds}`;
        }

        /**
         * 获取token
         */
        async function refreshToken()
        {
            var appId = "System";
            var secret = "Y2F0Y2yhciUyMHdvbmclMFWfsaZlJTIwLm5ldA==";
            var result = await fetchWithOutToken('/JwtToken?appid='+appId+'&secret='+secret);
            console.log(result);
            if(result.Success)
            {
                var data = result.ResData;
                console.log(data);
                var token = data.AccessToken;
                var expires_in = data.ExpiresIn
                var curTime = new Date();
                var expiredate = new Date(curTime.setMinutes(curTime.getMinutes() + expires_in));
                console.log(expiredate);
                setToken(token);
                localStorage.setItem('expiresIn', expires_in);
                localStorage.setItem('expireDate', expiredate);
            }
            else
            {
                console.log("错误码："+result.ErrCode+"；错误信息："+result.ErrMsg);
            }
        }

        /**
         * 不带token的请求方法
         * body 不为null时 需要传 JSON.stringify(body) 的数据
         */
        async function fetchWithOutToken(url, method = 'GET', body = null) {
            var options = {
                method : method,
                body : body
            }
            return await requestFetch(url, options);
        }

        /**
         * 带token的请求方法
         * body 不为null时 需要传 JSON.stringify(body) 的数据
         */
        async function fetchWithToken(url, method = 'GET', body = null) {
            let token = getToken();
            console.log("JwtToken: ", token);
            var isRefresh = false;
            if (token) 
            {
                let expireDate = localStorage.getItem('expireDate');
                let expiretime = new Date(Date.parse(expireDate))
                if(expiretime < new Date())
                {
                    isRefresh = true;
                }
            }
            else
            {
                isRefresh = true;
            }
            if(isRefresh)
            {
                console.log('Fetching new token...');
                await refreshToken(); // 重新获取token的函数
                token = getToken(); // 再次获取token以确保已经存储
            }
            console.log("JwtToken: ", token);
            var options = {
                method : method,
                body : body
            }
            return await requestFetch(url, options, token);
        }

        //设置缓存
        function setToken(newToken) {
            localStorage.setItem('auth_token', newToken);
        }

        //获取缓存
        function getToken() {
            return localStorage.getItem('auth_token');
        }

        /**
        * fetch请求公用方法
        */
        async function requestFetch(url, options = {}, token = null) {
            method = (options.method || 'GET').toUpperCase();
            if (method === 'GET') {
                // fetch的GET不允许有body，参数只能放在url中
                options.body = undefined;
            }
            options.method = method;
            options.headers = options.headers || {};
            options.headers['Content-Type'] = 'application/json';
            if (token) {
                options.headers['Authorization'] = `Bearer ${token}`;
            }
            try 
            {
                var response = await fetch(url, options);
                if (response.ok) 
                {
                    return await response.json();
                }
                else
                {
                    console.error('Fetching error: Network response was not ok');
                }
            } catch (error) {
                console.error('Fetching error:', error);
            }
        }

        // 使用示例
        // setToken('your_token_here');
        // fetchWithToken('https://api.example.com/data')
        //     .then(response => response.json())
        //     .then(data => console.log(data))
        //     .catch(error => console.error('Error:', error));

    </script>
}
